package service

import (
	"fmt"
	"go-web/dao"
	"go-web/entity"
	"go-web/env"
)

func UserAdd(name string, age int) {
	user := entity.User{
		Name: name,
		Age:  age,
	}

	dao.AddUser(user)
}

func UpdateTwoUser(users []entity.User) error {
	user1 := users[0]
	user2 := users[1]

	//开启事物
	tx := env.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			fmt.Println(r)
			//回滚事物
			tx.Rollback()
		}
	}()

	if err := dao.UpdateUser(tx, user1); err != nil {
		//回滚事物
		tx.Rollback()
		return err
	}

	if err := dao.UpdateUser(tx, user2); err != nil {
		//回滚事物
		tx.Rollback()
		return err
	}

	//提交事物
	return tx.Commit().Error
}
